<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

  <title>Vertical Playground</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="js/layer/theme/default/layer.css">
  <link rel="stylesheet" href="js/jquery-ui-1.12.1.custom/jquery-ui.min.css">
  <link rel="stylesheet" href="css/action_api.css">
  <link rel="stylesheet" href="css/index.css">
  <script src="js/jquery.min.js"></script>
  <script>/*loadxml.min.js*/eval(function(p,a,c,k,e,r){e=function(c){return c.toString(36)};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'[2-9a-i]'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(4(){var 3=c,6=false,7=location.search.7(/2=([^&=\\/]+)/),2=7?7[1]:\'simple\';$.ajax({url:\'js/2/\'+2+\'.5\',dataType:"5",success:4(d){2=$(d).find(\'5\').get(0);6=e;9(3){8.a(\'f 2-5 lazy!\');3()}},b:4(XMLHttpRequest,g,h){8.b(g,h);2=c;6=e;9(3){8.a(\'f 2-5 b!\');3()}}});i.toolboxReady=4(){3=4(){start()};9(6){8.a(\'loaded 2-5!\');3()}};i.toolboxXml=4(){return 2}}());',[],19,'||toolbox|callback|function|xml|status|match|console|if|info|error|null|data|true|load|textStatus|errorThrown|window'.split('|'),0,{}))</script>


  <!-- ******************debug model*********************** -->
   <!--<script src="../../../blockly/blockly_uncompressed_vertical.js"></script>-->
  <!--<script src="../../../blockly/msg/messages.js"></script>-->
  <!--<script src="../../../blockly/msg/js/zh-hans.js"></script>-->

  <!--<script src="../../../blockly/blocks_vertical/vertical_extensions.js"></script>-->
  <!--<script src="../../../blockly/blocks_common/math.js"></script>-->
  <!--<script src="../../../blockly/blocks_common/text.js"></script>-->
  <!--<script src="../../../blockly/blocks_common/colour.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/control.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/event.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/motion.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/looks.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/procedures.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/operators.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/pen.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/sound.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/sensing.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/data.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/inout.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/default_toolbox.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/customs.js"></script>-->
  <!--<script src="../../../blockly/blocks_vertical/servo.js"></script>-->

  <!--<script src="../../../blockly/generators/arduino.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/logic.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/math.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/control.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/text.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/data.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/inout.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/customs.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/servo.js"></script>-->
  <!--<script src="../../../blockly/generators/arduino/motion.js"></script>-->

  <!--<script type="application/javascript" src="../../../blockly/generators/javascript.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/logic.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/math.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/motion.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/control.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/text.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/data.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/inout.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/servo.js"></script>-->
  <!--<script type="application/javascript" src="../../../blockly/generators/javascript/customs.js"></script>-->
  <!-- *********************end debug****************************** -->


  <!-- ************************release model************************************* -->
  <script type="application/javascript" src="../../blockly_compressed_vertical.js"></script>
  <script src="../../blocks_compressed.js"></script>
  <script type="application/javascript" src="../../blocks_compressed_vertical.js"></script>
  <script type="application/javascript" src="../../arduino_compressed.js"></script>
  <script type="application/javascript" src="../../javascript_compressed.js"></script>
  <script src="../../../blockly/msg/messages.js"></script>
  <script src="../../../blockly/msg/js/zh-hans.js"></script>
  <!-- ************************** end release********************************** -->








  <script src="js/Blob.js"></script>
  <script src="js/spin.js"></script>
  <script src="js/FileSaver.min.js"></script>
  <script src="js/blockly_helper.js"></script>
  <script src="js/mikuCanvasImageUtil.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jszip.min.js"></script>

  <script src="js/layer/layer.js"></script>
  <script src="js/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>
  <script src="js/action_api.js"></script>
  <script src="js/spark-md5.js"></script>
  <script src="js/tool.js"></script>
  <script src="js/uploads-core.js"></script>
  <script src="js/index.js"></script>
  <script src="js/qwebchannel.js"></script>
</head>

<body onload="toolboxReady()">

<div class="meta-nav">
  <nav class="navbar navbar-top navbar-inverse">
    <div class="container-fluid">
      <div class="">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">
            <img alt="Brand" src="img/logo.png">
          </a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav navbar-left navbar-nav-top">
            <li>
              <a href="#" class="download dropdown-toggle" data-toggle="dropdown" aria-haspopup="true"
                 aria-expanded="false">文件<span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="javascript:void(0)" onclick="new_empty_project()">新建空工程</a></li>
                <li><a href="javascript:void(0)" onclick="save()">保存工程</a></li>
                <li><a href="javascript:void(0)" id="fakeload">加载工程</a>
                  <input type="file" id="load" accept="mt" style="display: none;"/>
                </li>
              </ul>
            </li>
            <li>
              <a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true"
                 aria-expanded="false">编辑<span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li class="dropdown-submenu">
                  <a href="#">板子选择<span></span></a>
                  <ul class="dropdown-menu">
                    <li class="board"><i class="glyphicon glyphicon-ok" style="display: none"></i><a
                      href="javascript:void(0)" value="arduino:avr:nano:cpu=atmega328" onclick="select_board(this)">arduino
                      nano</a></li>
                    <li class="board"><i class="glyphicon glyphicon-ok" style="display:none"></i><a
                      href="javascript:void(0)" value="arduino:avr:uno" onclick="select_board(this)">arduino uno</a>
                    </li>
                  </ul>
                </li>
                <li class="dropdown-submenu">
                  <a href="#">板子连接方式<span></span></a>
                  <ul class="dropdown-menu">
                    <li class="board-connect"><i class="glyphicon glyphicon-ok" style="display: none"></i><a href="javascript:void(0)" value="0" onclick="select_board_connect_type(this)">串口连接</a></li>
                    <li class="board-connect"><i class="glyphicon glyphicon-ok" style="display:none"></i><a href="javascript:void(0)" value="1" onclick="select_board_connect_type(this)">蓝牙连接</a>
                    </li>
                  </ul>
                </li>
                <!--<li><a href="#">端口</a></li>-->
              </ul>

            </li>
               <li>
              <a href="#" class="download dropdown-toggle" data-toggle="dropdown" aria-haspopup="true"
                 aria-expanded="false">帮助<span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="javascript:void(0)" data-toggle="modal" data-target="#myModal">关于</a></li>
                <li><a href="javascript:void(0)" data-toggle="modal" data-target="#myModal02">授权同意书</a></li>

              </ul>
            </li>
            <!--<li><a href="javascript:void(0)" class="">帮助</a></li>-->
            <!--<li><a href="javascript:void(0)" data-toggle="modal" data-target="#myModal">关于</a></li>-->

          </ul>
        </div>
      </div>
    </div>
  </nav>
</div>


<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="margin-top:20%">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
          aria-hidden="true">&times;</span></button>
        <img alt="Brand" src="img/logo.png">
      </div>
      <div class="modal-body">
        <p>本软件所属公司是广州艾考教育科技有限公司</p>
        <p>名人才编程 v1.0.2版本</p>
        <p>开发人员 Jack He、Kellen zhang</p>
        <p>MRC编程软件最后解释权所属于广州艾考教育科技有限公司</p>
      </div>
      <!--    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
      </div> -->
    </div>
  </div>
</div>

<!--授权书弹窗-->
<div class="modal fade" id="myModal02" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" >
  <div class="modal-dialog" role="document" style="width:1200px;">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
          aria-hidden="true">&times;</span></button>
        <img alt="Brand" src="img/logo.png">
      </div>
      <div style="padding: 20px 40px;">
        <p>授权书</p>
        <p>信息授权协议（以下简称“本协议”）是广州艾考教育科技有限公司（以下简称“艾考”）在使用”MetasLab-MRC编程平台（以下简称“平台”）时，与用户 (以下简称“您”)就个人信息授权使用所订立的合约。</p>
         <p>您通过应用授权页面点击确认，即表示您同意接受本协议的全部约定内容以及与本协议有关的已经发布或将来可能发布的各项规则、页面展示、操作流程、公告或通知（以下统称“规则 ” ）。</p>
         <p>在接受本协议之前，请您仔细阅读本协议的全部内容 （特别是以粗体下划线标注的内容）。如果您不同意本协议的任意内容，或者无法准确理解该条款的含义，请不要进行任何操作。</p>
         <p>一、您同意并授权艾考将您的个人信息提供给支付宝（中国）网络技术有限公司（以下简称“支付宝”），深圳市腾讯计算机系统有限公司（以下简称“腾讯”），以用于您向平台第三方登录操作。</p>
         <p>二、本协议中的个人信息，包括但不限于： </p>
         <p>1、您的个人电脑/设备信息；</p>
         <p>2、您的课程设计内容；</p>
         <p>3、您在”平台“留存的操作信息，包括但不限于操作日志；</p>
         <p>三、您同意本协议中的授权不可撤回或撤销。</p>
         <p>四、您同意，因履行本协议发生纠纷的，任何一方应向被告住所地人民法院提起诉讼。</p>
         <p></p>
      </div>
    </div>
  </div>
</div>
<!--启动页面授权书-->
<div class="attorney" style="display: none">
    <div class="attorneyin">
        <img alt="Brand" src="img/logo.png" class="attlogo">
        <h3 class="atttitle">授权书</h3>
        <p>信息授权协议（以下简称“本协议”）是广州艾考教育科技有限公司（以下简称“艾考”）在使用”MetasLab-MRC编程平台（以下简称“平台”）时，与用户 (以下简称“您”)就个人信息授权使用所订立的合约。</p>
        <p>您通过应用授权页面点击确认，即表示您同意接受本协议的全部约定内容以及与本协议有关的已经发布或将来可能发布的各项规则、页面展示、操作流程、公告或通知（以下统称“规则 ” ）。</p>
        <p>在接受本协议之前，请您仔细阅读本协议的全部内容 （特别是以粗体下划线标注的内容）。如果您不同意本协议的任意内容，或者无法准确理解该条款的含义，请不要进行任何操作。</p>
        <p>一、您同意并授权艾考将您的个人信息提供给支付宝（中国）网络技术有限公司（以下简称“支付宝”），深圳市腾讯计算机系统有限公司（以下简称“腾讯”），以用于您向平台第三方登录操作。</p>
        <p>二、本协议中的个人信息，包括但不限于： </p>
        <p>1、您的个人电脑/设备信息；</p>
        <p>2、您的课程设计内容；</p>
        <p>3、您在”平台“留存的操作信息，包括但不限于操作日志；</p>
        <p>三、您同意本协议中的授权不可撤回或撤销。</p>
        <p>四、您同意，因履行本协议发生纠纷的，任何一方应向被告住所地人民法院提起诉讼。</p>
         <!--<p><input type="checkbox" class="agreed" value=""/> 我已阅读并协议同意授权</p>-->
         <p class="attobut"><input type="button" value="同意" class="agreedin" agree="1"/><input type="button" value="不同意" agree="2"/></p>
      </div>
</div>

<div class="">
  <div class="">
    <div class="col-md-4 col-sm-12 left-contain" style="padding-right: 0px;">
      <div class="img-block">
        <div class="pre-img-block">
          <div class="pre-img-head">
            <div class="icon-1"><img src="img/fangda.png" style="float:left">
                <p style="float:left;margin-left:10px;display:none" id="project_name"></p>
            </div>
              <div class="icon-2 character_start"><img src="img/hongqi.png"></div>
            <div class="icon-2" id="character_reset"><img src="img/tingzhi.png"></div>
          </div>
          <div class="pre-img-show">
            <div class="pre-img" id="operating-space">
              <div data-role="BlockAction" id="action-block"><img src="./img/human/753c35deaf4b507f.png"></div>
            </div>
          </div>
          <div class="pre-control">
            <!--<span class="pre-c1" style="margin-left:10px"><img src="img/fuzhi.png"></span>-->
            <span class="pre-c1"><img class="clearAreaBtn" src="img/shanchu.png"></span>
            <span class="pre-c1"><img class="inAreaBtn" src="img/da.png"></span>
            <span class="pre-c1"><img class="outAreaBtn" src="img/xiao.png"></span>
          </div>
        </div>
      </div>
      <div class="coordinate">
        <span> x: 270 y: 47</span>
      </div>
      <div class="small-block">
        <div class="small-head">
          <div style="float:left;margin-left:85px"><span>人物</span></div>
          <div class="icon-6"><img src="img/shangchuan.png" class="myUploads" data-type="human"></div>
          <!--<div class="icon-5"><img src="img/huabi.png"></div>-->
          <div class="icon-4"><img src="img/renwu.png" class="openLibrary" data-type="human"></div>
        </div>
        <div class="small-foot">
          <div class="icon-3"><img src="img/tupian.png" class="openLibrary" data-type="background"></div>
          <div class="icon-6"><img src="img/shangchuan.png" class="myUploads" data-type="background"></div>
        </div>
        <div class="d-line"></div>
        <div class="small-show">
          <div class="small-show-left">
            <div class="bg-container myscrollbar">
              <div class="bgk" data-clear="true">
                <img src="./img/juxingkuang.png" data-init="true">
                <p>背景1</p>
              </div>
            </div>
          </div>
          <section class="small-show-right hm-container myscrollbar" id="changeImg">
            <div class="change-img active"><img src="./img/human/753c35deaf4b507f.png" data-init="true"></div>
            <div class="change-img"><img src="./img/human/5f1decb5302f330b.png" data-init="true"></div>
          </section>
        </div>

      </div>
    </div>
    <div class="col-md-8 col-sm-12">
      <div>
        <div class="all right-content" id="box">
          <h2 id="tabRow" class="Conbutleft">
            <span style="background:#999;color:#fff;border-radius:6px 0px 0px 0px" id="tab_blocks">模块</span>
            <span id="tab_arduino">触发</span>
            <span style="margin:0;border-radius:0px 6px 0px 0px" id="tab_xml">XML</span>
          </h2>
          <h3 class="Conbutright">
            <i><img src="/blockly/apps/blocklyduino/img/hong.png" width="8%" class="connect_state" title="未连接到arduino"></i>
            <button type="button" onclick="uploadClick()">上传</button>
            <button type="button" onclick="resetClick()">重置</button>
            <button onclick="discard()">删除</button>
            <!--   <button onclick="saveCode()">Save Arduino Code</button>
            <button onclick="save()">Save XML</button>
            <button id="fakeload" onclick="fakeload()">Load XML</button>
            <input type="file" id="load" accept="xml" style="display: none;"/> -->
          </h3>
          <a style="display:block;" id="content_blocks"></a>
          <a>
            <textarea id="content_arduino" class="content" readonly wrap="off"></textarea>
          </a>
          <a>
            <textarea id="content_xml" class="content" wrap="off"></textarea>
          </a>
        </div>

      </div>
    </div>
  </div>
</div>

<script>

  $.ajax({
        url: "http://"+window.location.host+"/agree_state/",
        type: "Get",
        async: false,
        dataType: "text",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
          // var parse_data=JSON.parse(data);
          if(data=="1" || data=="2"){
            $(".attorney").hide();
          }
          else{
            $(".attorney").show();
          }
        }
      });


  window.onresize = function () {
//  // changeFrameHeight();
    if ($(window).width() > 1000) {
      $(".left-contain,.right-content").height($(window).height() - 100);
    }
    ;

    var d_height = $(".small-block").height() - 36
    $(".d-line").css({"height": d_height, "top": "36px"})
    $(".small-show").css({"height": d_height});

  };
  $(window).resize();
  $(document).ready(function () {
    $(".left-contain,.right-content").height($(document).height() - 100);
    var d_height = $(".small-block").height() - 36;
    $(".d-line").css({"height": d_height, "top": "36px"})
    $(".small-show").css({"height": d_height});
    /*var oUl = document.getElementById('changeImg');
    oUl.addEventListener('click', function (ev) {
      var target = ev.target;
      while (target !== oUl) {
        if (target.tagName.toLowerCase() == 'img') {
          var imgurl = target.getAttribute("src")
          $(".pre-img img").attr("src", imgurl)
          break;
        }
        target = target.parentNode;
      }
    })*/
  });

  function renderContent(count) {
    if (count == 1) {
      var arduinoTextarea = document.getElementById('content_arduino');
      arduinoTextarea.value = Blockly.Arduino.workspaceToCode(Blockly.mainWorkspace);
      arduinoTextarea.focus();
    }
    else if (count == 2) {
      var xmlTextarea = document.getElementById('content_xml');
      var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
      var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
      xmlTextarea.value = xmlText;
      xmlTextarea.focus();
    }

  }

  function tab(a) {
    var obox = document.getElementById(a);
    var spans = obox.getElementsByTagName('span');
    var divs = obox.getElementsByTagName('a');
    for (var i = 0; i < spans.length; i++) {
      spans[i].index = i;
      spans[i].onclick = function () {
        for (var i = 0; i < spans.length; i++) {
          spans[i].style.background = '#fff';
          spans[i].style.color = '#333'
          divs[i].style.display = 'none'
          renderContent(i)
        }
        this.style.background = '#999'
        this.style.color = '#fff'
        divs[this.index].style.display = 'block'
      }
    }
  }

  tab('box');

  // function fakeload(e) {
  //   var on_load=document.getElementById('load');
  //   on_load.click();
  // }

  // document.getElementById('load').addEventListener('change', load, false)

  function post_select_board(code, callback) {

    var url = "http://" + window.location.host + '/select_board/';
    var method = "POST";

// You REALLY want async = true.
// Otherwise, it'll block ALL execution waiting for server response.
    var async = true;

    var request = new XMLHttpRequest();


    request.onreadystatechange = function () {
      if (request.readyState != 4) {
        return;
      }
      var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
      var errorInfo = null;
      switch (status) {
        case 200:
          break;
        case 0:
          errorInfo = "code 0\n\n 不能连接到服务器 " + url + ".  请确认服务器是否允许?";
          break;
        case 400:
          errorInfo = "code 400\n\n选择板子失败.";
          break;
        case 500:
          errorInfo = "code 500\n\n选择板子失败，服务器内部错误. ";
          break;
        case 501:
          errorInfo = "code 501\n\n选择板子失败，服务器内部错误.";
          break;
        default:
          errorInfo = "code " + status + "\n\n未知错误.";
          break;
      }
      ;

      callback(status, errorInfo);
    };

    request.open(method, url, async);
    request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    request.send(code);
  }

  function select_board(el) {
    var board = el.getAttribute("value");
//             alert("当前选项是:"+board);
    var parent_el = $(el).parent("li");
    var ul_parent_el = $(el).parent("li").parent("ul");
    post_select_board(board, function (status, errorInfo) {
      if (status == 200) {
        ul_parent_el.find("i").css("display", "none");
        parent_el.find("i").css("display", "block");
        alert("选择板成功");
      } else {
        alert("选择板失败: " + errorInfo);
      }
    });
  }
</script>
<script>
/**
 * 关于块、背景、人物操作等方法与监听
 * 对外接口：
 *   ActionBlock: 块行动控制对象;
 *   createBackground: 创建背景方法, 用于背景添加的行内 js 调用;
*                      createBackground(url:图片路径)
 *   createHuman:   创建人物方法, 用于背景人物的行内 js 调用;
 *                  createHuman(url:图片路径)
 *   getSaveConfig: 获取保存配置方法;
 *                  createHuman(string:是否返回字符串)
 *   initByConfig:  使用配置进行初始化方法;
 *                  initByConfig(config:getSaveConfig 返回的配置信息, string:是否传入字符串)
 * @author OJesusO
 */
(function(areaObj, hmContainer, bgContainer, doc, W){
    //详细的块行动控制 http://ojesuso.gitee.io/action_api_class/
    //实例化 BlockAction, 用于控制块的行动操作
    W.ActionBlock = new BlockAction('#action-block', {
        images: getHumanImgsrc(),
        moveStep: 1,
    });
    function openDraggable () {
        ActionBlock.elementObj.draggable({
            grid: [1, 1],
            start: function(evt, ui) {
                ActionBlock.transition = ui.helper.css('transition');
                ui.helper.css({
                    transition: 'none',
                });
            },
            drag: function(evt, ui) {
            },
            stop: function(evt, ui) {
                ui.helper.css({
                    transition: ActionBlock.transition,
                });
            },
            containment: 'parent',
        });
    }; openDraggable();

    //监听图片改变, 切换 ActionBlock 的背景 | 如果操作空间为空 放置内容
    hmContainer.on('click', '.change-img', function(){
        if (areaObj.find(ActionBlock.elementObj).length == 0) {
            ActionBlock.elementObj.appendTo(areaObj);
            openDraggable();
        }
        var src = $(this).find('img').attr('src');
        ActionBlock.changeImage(src, 150, 'auto');
        hmContainer.find('.change-img').not($(this)).removeClass('active');
        $(this).addClass('active');
    }).find('img').each(function(){
        setImageId(this);
    });

    //监听背景切换
    bgContainer.on('click', '.bgk', function(){
        var src = $(this).find('img').attr('src');
        if ($(this).data('clear')) {
            areaObj.css({
                backgroundImage: 'none',
            }).data('bgSrc', '');
        } else {
            areaObj.css({
                backgroundImage: 'url('+ src +')',
            }).data('bgSrc', src);
        }
    }).find('img').each(function(){
        setImageId(this);
    });
    areaObj.data('bgSrc', '');

    //清空操作空间
    $('.clearAreaBtn').click(function(){
        ActionBlock.elementObj.remove();
        hmContainer.find('.change-img').removeClass('active');
    });

    //放大操作空间
    $('.inAreaBtn').click(function(){
        areaObj.css('zoom', Zoom.in());
    }).mousedown(function(e){
        if (3 == e.which) {
            areaObj.css('zoom', Zoom.max());
        }
    }).bind("contextmenu", function(){
        return false;
    });

    //缩小操作空间
    var outAreaBtn = $('.outAreaBtn');
    outAreaBtn.click(function(){
        areaObj.css('zoom', Zoom.out());
    }).mousedown(function(e){
        if (3 == e.which) {
            areaObj.css('zoom', Zoom.min());
        }
    }).bind("contextmenu", function(){
        return false;
    });

    //倍率放大逻辑
    var Zoom = (function(prevBtnObj){
        var maxZoom = 2, minZoom = .1,
        zoom = 1, cancelBtn = null;
        function toZoom (type) {
            if (type === true) {
                zoom += .1;
            } else if (type === false) {
                zoom -= .1;
            } else {
                zoom = type
            }
            if (zoom > maxZoom) {
                zoom = maxZoom;
            } else if (zoom < minZoom) {
                zoom = minZoom;
            }
            toggleCancelBtn(zoom != 1);
            return zoom;
        };
        function toggleCancelBtn (type) {
            if (!cancelBtn) {
                cancelBtn = $(doc.createElement('span'));
                cancelBtn.addClass('pre-c1');
                cancelBtn.html('<img class="cancelZoomBtn" src="img/cexiao.png">');
            }
            if (type) {
                if (prevBtnObj.parent().find(cancelBtn).length == 0) {
                  prevBtnObj.after(cancelBtn);
                  cancelBtn.find('img').click(function(){
                      toZoom(1);
                  });
                }
            } else {
                cancelBtn.remove();
                areaObj.css('zoom', zoom);
            }
        };
        return {
            in: function(){ return toZoom(true) },
            out: function(){ return toZoom(false) },
            max: function(){ return toZoom(maxZoom) },
            min: function(){ return toZoom(minZoom) },
        };
    }(outAreaBtn.parent()));

    //鼠标位置记录
    var areaOffset = areaObj.offset();
    areaObj.mousemove(function(evt){
        var xy = getCoordinateByEvent(evt);
        $('.coordinate span').text(' x: '+ xy[0] +' y: '+ xy[1]);
    });
    function getCoordinateByEvent (evt) {
        //new goog.math.Coordinate();
        return [evt.pageX - areaOffset.left, evt.pageY - areaOffset.top];
    };

    //上传操作功能
    (function(){
        var upload_type = null;
        var uploadCore = new UploadsCore({
            debug: 1,
            inputId: 'uploadcore-input',
            fileType: ['image'],
            uploadURL: '/upload_file/',
            fileSuffix: {'image':['png', 'jpg', 'jpeg']},
            initpostBeforeCallback: function (file) {
                //初始化上传前回调
                return {
                    postData: {
                        upload_type: upload_type,
                        file_name: file.name,
                        file_type: file.type,
                    }
                };
            },
            getMd5ingCallback: function (file, loaded, total) {
                //获取md5中回调
            },
            waitingCallback: function (data) {
                //等待上传中回调
            },
            startingCallback: function (data) {
                //开始上传中回调
            },
            progressCallback: function (data) {
                //上传传输中回调
            },
            successCallback: function (data) {
                //上传成功后回调
                data = data.response;
                switch (data.upload_type) {
                  case 'background':
                        /*createBackground(data.url);*/ break;
                    case 'human':
                        /*createHuman(data.url);*/ break;
                    default:
                        return TOOL.error('文件上传出错！');
                }
                TOOL.successMsg('上传成功！');
            },
            failCallback: function (data) {
                //上传失败后回调
                TOOL.error('上传失败！');
            },
            endedCallback: function (data) {
                //结束上传后回调
            },
            errorCallback: function (data) {
                //失败后回调
            },
        }),
        input = $('#uploadcore-input');
        $('.myUploads').click(function(){
            var type = $(this).data('type');
            upload_type = type;
            input.click();
        }).css({
            cursor: 'pointer',
        });
    }());

    //读取列表功能
    (function(){
        var dir = '/blockly/apps/blocklyduino/img/';
        $('.openLibrary').click(function(){
            var type = $(this).data('type'),
            path = dir + type + '/';
            switch (type) {
                case 'background': break;
                case 'human': break;
                default: return TOOL.error('读取文件列表出错！');
            }
            $.ajax({
                url: 'http://127.0.0.1:8080' + path,
                success: function(data){
                    var obj = $(doc.createElement('div'));
                    obj.html(data);
                    obj = obj.html(obj.find('ul'));
                    layer.open({
                        type: 1,
                        shadeClose: true,
                        area: ['465px', '380px'], //宽高
                        content: obj.html(),
                        title: '选择' + (type=='background' ? '背景' : '人物'),
                        success: function(layero, index){
                            switch (type) {
                                case 'background':
                                    var callback = 'createBackground'; break;
                                case 'human':
                                    var callback = 'createHuman'; break;
                            }
                            layero.find('ul').attr('id', 'images-list');
                            layero.find('li>a').each(function(){
                                var src = path + $(this).attr('href');
                                $(this).attr('href', 'javascript:'+ callback +'(\''+ src +'\');layer.close('+ index +');');
                                $(this).html('').css({
                                    backgroundImage: 'url('+src+')',
                                });
                            });
                        },
                        end: function(layero){
                            switch (type) {
                                case 'background':
                                    var obj = bgContainer; break;
                                case 'human':
                                    var obj = hmContainer; break;
                            }
                            obj.animate({
                                scrollTop: obj[0].scrollHeight,
                            }, 300);
                        },
                    });
                },
                error: function(){
                    TOOL.errorMsg('读取文件列表出错！');
                },
            });
        }).css({
            cursor: 'pointer',
        });
    }());

    //创建背景
    W.createBackground = function (url) {
        if (hasBgid(url)) {
            return false;
        }
        var obj = $(doc.createElement('div'));
        obj.addClass('bgk');
        obj.html('<img src="'+ url +'"><p>背景'+ (bgContainer.find('.bgk:last').index()+2) +'</p>');
        bgContainer.append(obj);
        setImageId(obj.find('img'));
        return obj;
    };

    //创建人物
    W.createHuman = function (url) {
        if (hasHmid(url)) {
            return false;
        }
        var obj = $(doc.createElement('div'));
        obj.addClass('change-img');
        obj.html('<img src="'+ url +'">');
        hmContainer.append(obj);
        setImageId(obj.find('img'));
        ActionBlock.Images.set(url);
        return obj;
    };

    //创建图片唯一Id
    function getImageId (src) {
        return SparkMD5.hash(src.split('/').pop());
    };
    function setImageId (obj) {
        obj = $(obj);
        obj.attr('data-id', getImageId(obj.attr('src')));
    };
    function hasHmid (src) {
        var nowId = getImageId(src);
        return hmContainer.find('img[data-id="'+ nowId +'"]').length > 0;
    };
    function hasBgid (src) {
        var nowId = getImageId(src);
        return bgContainer.find('img[data-id="'+ nowId +'"]').length > 0;
    };

    //获取保存配置
    W.getSaveConfig = function (string) {
        var config = {
            backgrounds: getBackgroundImgsrc(),
            humans: getHumanImgsrc(),
            currentBg: areaObj.data('bgSrc'),
            currentHm: ActionBlock.elementObj.find('img').attr('src'),
        };
        return string ? TOOL.jsonStrify(config) : config;
    };
    function getHumanImgsrc () {
        var humans = [];
        hmContainer.find('img').each(function(){
            humans.push($(this).attr('src'));
        });
        return humans;
    };
    function getBackgroundImgsrc () {
        var backgrounds = [];
        bgContainer.find('img').each(function(){
            if ($(this).parent().data('clear')) {
                return true;
            }
            backgrounds.push($(this).attr('src'));
        });
        return backgrounds;
    };

    //使用配置进行初始化
    W.initByConfig = function (config, string) {
        if (string) {
            config = TOOL.jsonParse(config);
        }
        config = config || {};
        initHumanImage(config.humans);
        initBackgroundImage(config.backgrounds);
        setTimeout(function(){
            initCurrentHm(config.currentHm);
            initCurrentBg(config.currentBg);
        }, 100);
    };
    function initHumanImage (humans) {
        hmContainer.find('img').not('[data-init="true"]').parent().remove();
        $.each(humans, function(key, src){
            var obj = createHuman(src);
            if (obj) {
                obj.find('img').on('error', function(){
                    if (ActionBlock.elementObj.find('img').attr('src') == $(this).attr('src')) {
                        hmContainer.find('img[data-init]').first().click();
                    }
                    obj.remove();
                });
            }
        });
    };
    function initBackgroundImage (backgrounds) {
        bgContainer.find('img').not('[data-init="true"]').parent().remove();
        $.each(backgrounds, function(key, src){
            var obj = createBackground(src);
            if (obj) {
                obj.find('img').on('error', function(){
                    obj.remove();
                });
            }
        });
    };
    function initCurrentHm (hm) {
        if (!hm) {
            return false;
        }
        hm = getImageId(hm);
        hmContainer.find('img[data-id="'+ hm +'"]').click()
    };
    function initCurrentBg (bg) {
        if (!bg) {
            return false;
        }
        bg = getImageId(bg);
        bgContainer.find('img[data-id="'+ bg +'"]').click();
    };

    //放大|缩小操作区域
    var maxSpaceWin = null;
    $('.pre-img-head .icon-1 img').click(function(){
        if ($(this).data('ismax')) {
            layer.close(maxSpaceWin);
        } else {
            openMaxSpace($(this));
        }
    });
    function openMaxSpace (btn) {
        maxSpaceWin = layer.open({
            type: 1,
            shade: true,
            shadeClose: true,
            closeBtn: 0,  //不显示关闭按钮
            title: false, //不显示标题
            content: $('.pre-img-block'),
            success: function(layero, index){
                btn.data('ismax', true).attr('src', './img/suoxiao.png');
                layero.css({
                    width: '90%',
                    height: '80%',
                }).find('.layui-layer-content').css({
                    height: '100%',
                });
                $(window).resize();
            },
            end: function(){
                btn.data('ismax', null).attr('src', './img/fangda.png');
            },
        });
    };


    $("#character_reset").click(function(){
        ActionBlock.isAction();
        ActionBlock.reset();
    });

    function get_blockly_javascript(){
        /*获取积木的javascript代码，返回一个代码执行的函数地址*/
        var javascript_text=Blockly.JavaScript.workspaceToCode(Blockly.mainWorkspace);
         function character_motion (){
            eval(javascript_text);
        }
        console.info(javascript_text);
        return character_motion;
    }
    $(".character_start").click(function(){
        var character_motion=get_blockly_javascript();
        try{
            character_motion();
        }
        catch (e){
            alert("执行积木命令运动错误，"+e);
        }

      // new QWebChannel(qt.webChannelTransport, function (channel) {
      //     window.handler = channel.objects.handler;
      //     window.handler.run_websocket();
      // });

    });

}(
  $('#operating-space'),  //操作空间
  $('.hm-container'),     //人物容器
  $('.bg-container'),     //背景容器
  document, window
));
//授权书
//   $('.agreed').click(function(){
//       $('.attobut input').eq(0).toggleClass('attcent');
//
//   });
//
//   $('.agreedin').click(function(){
//       if($('.agreed').is(":checked")){
//          $(this).parent().parent().parent().hide();
//       }else{
//           $(this).parent().parent().parent().show();
//       }
//   })
   $('.attobut input').click(function(){
       $(this).parent().parent().parent().hide();
       var agree=$(this).attr("agree");
       $.ajax({
        url: "http://"+window.location.host+"/post_agree_state/",
        type: "Post",
        async: false,
        data:agree,
        dataType: "text",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);
        },
        success: function (data) {
          $(".attorney").hide();
        }
      });

   });



</script>

</body>
</html>
